package com.eagle.roomsearch.controller.webSocketController;

import lombok.ToString;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;

/*1.問題：解決webSocket用SringBoot 和Tomcat 啟動 不通啟動方式 出現的問題？
// 問題產生原因：應該是 Tomcat 容器 和 Spring 都去管理 webSocket
// 解決方法：用Spring Boot啟動要用prototype ，不然會和WebSocketConfig的ServerEndpointExporter衝突
// 用Tomcat 啟動的話 刪掉WebSocketConfig 和 @Scope("prototype")
 */
@Scope("prototype")
@ServerEndpoint(value = "/websocket/{userNumber}", encoders = WebSocketEncoder.class)
@Component
@ToString
public class WebSocketController implements Serializable {

    private Session session;
    private String userNumber;

    @OnOpen
    public void onOpen(@PathParam(value = "userNumber") String userNumber, Session session) {
        this.userNumber = userNumber;
        this.session = session;
        Message message = new Message();
        message.setTime(LocalDateTime.now());

        if (1 != 0) {
            WebSocketOnlineCount.addOnlineCount();
            System.out.println(userNumber + "上线了，目前在线人数：" + WebSocketOnlineCount.getOnlineCount());
            WebSocketHashTable.save(userNumber, this);
//            message.setMessage(userInformation.getUserName() + "上线了");
//            sendMessage(message);
        } else {
            message.setMessage("id : [" + userNumber + "] 错误");
            sendMessage(message);
            this.onClose();
        }
    }


    @OnClose
    public void onClose() {
        WebSocketHashTable.remove(userNumber);
        WebSocketOnlineCount.subOnlineCount();
        System.out.println(userNumber + "下线了，目前在线人数：" + WebSocketOnlineCount.getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        System.out.println("session:=" + session);
    }

    public void sendMessage(Message message) {
        System.out.println("WebSocketController===" + message);
        System.out.println("session===" + session);

        try {
            this.session.getBasicRemote().sendObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EncodeException e) {
            e.printStackTrace();
        }
    }
}
